import requests
from bs4 import BeautifulSoup
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkalimt.request.v20181012 import TranslateGeneralRequest

# 配置阿里云翻译API的访问参数
client = AcsClient('LTAI5tQU8UqYracVUvMgCmGk', 'Xboes0i18qi1ccvf74CvNY6dfEcgKD', 'cn-hangzhou')

def translate_text(text):
    """Translate text to Chinese using Alibaba Cloud Translation API."""
    if not text:
        print(f"警告: 尝试翻译空文本")
        return None

    request = TranslateGeneralRequest.TranslateGeneralRequest()
    request.set_accept_format('json')
    request.set_SourceLanguage("en")
    request.set_TargetLanguage("zh")
    request.set_FormatType("text")
    request.set_SourceText(text)

    try:
        response = client.do_action_with_exception(request)
        result = json.loads(response)
        print(f"API响应: {result}")  # 打印完整的API响应
        translated_text = result.get('Data', {}).get('Translated')
        if not translated_text:
            print(f"警告: 未找到翻译结果, 原文: {text}")
        return translated_text
    except Exception as e:
        print(f"翻译错误: {e}, 原文: {text}")
        return None

def fetch_main_page():
    base_url = "https://www.astronomy.com/picture-of-the-day/"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

    response = requests.get(base_url, headers=headers)

    if response.status_code != 200:
        print(f"请求失败, 状态码: {response.status_code}, URL: {base_url}")
        return []

    soup = BeautifulSoup(response.content, 'html.parser')

    news_items = []

    for item in soup.select('article'):
        # 获取标题
        title_tag = item.select_one('h3.card-title a')
        if not title_tag:
            continue

        title = title_tag.get_text(strip=True)
        link = title_tag['href']

        # 获取缩略图
        thumbnail_tag = item.select_one('img')
        thumbnail = thumbnail_tag['src'] if thumbnail_tag else None

        # 打印原文
        print(f"原文标题: {title}")

        # 翻译标题
        translated_title = translate_text(title)

        news_item = {
            'title': translated_title,
            'thumbnail': thumbnail,
            'summary': None,
            'link': link  # 保存链接以便后续使用
        }
        news_items.append(news_item)

    return news_items

def read_json_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        return []
    except json.JSONDecodeError:
        print("JSON文件格式错误")
        return []

def write_json_file(file_path, data):
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)

def update_news_items(current_items, new_items):
    current_links = {item['link'] for item in current_items}
    updated_items = current_items.copy()
    updated = False

    for new_item in new_items:
        if new_item['link'] not in current_links:
            updated_items.insert(0, new_item)  # 将新新闻插入到列表开头
            print(f"新增新闻: {new_item['title']}")
            updated = True
        else:
            for item in updated_items:
                if item['link'] == new_item['link']:
                    if item['title'] != new_item['title'] or item['thumbnail'] != new_item['thumbnail']:
                        print(f"更新新闻: {item['title']} -> {new_item['title']}")
                        item.update(new_item)
                        updated = True
                    break

    # 去重逻辑：确保 updated_items 中没有重复的链接
    unique_items = []
    seen_links = set()
    for item in updated_items:
        if item['link'] not in seen_links:
            unique_items.append(item)
            seen_links.add(item['link'])

    return unique_items

if __name__ == '__main__':
    json_file_path = 'picture_item.json'
    current_news_items = read_json_file(json_file_path)

    new_news_items = fetch_main_page()

    if not new_news_items:
        print("没有找到新闻内容")
        exit(1)

    updated_news_items = update_news_items(current_news_items, new_news_items)

    # for item in updated_news_items:
    #     print(f"翻译后标题: {item['title']}")
    #     print(f"缩略图: {item['thumbnail']}")
    #     print("-" * 80)

    write_json_file(json_file_path, updated_news_items)
